CODE 60. Set Matrix Zeroes

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/10/05/2013-10-05-CODE 60 Set Matrix Zeroes/

访问原文「CODE 60. Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.click to show follow up.
Follow up:Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m+n) space, but still not the best solution.
Could you devise a constant space solution?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public void setZeroes(int[][] matrix) {
// Note: The Solution object is instantiated only once and is reused by
// each test case.
int zeroH = -1;
int rows = matrix.length;
int cols = matrix[0].length;
if (0 == matrix[0][0]) {
zeroH = 0;
}
for (int i = 1; i < rows; i++) {
if (0 == matrix[i][0]) {
matrix[0][0] = 0;
break;
}
}
for (int i = 1; i < cols; i++) {
if (0 == matrix[0][i]) {
zeroH = 0;
break;
}
}
for (int i = 1; i < rows; i++) {
for (int j = 1; j < cols; j++) {
if (0 == matrix[i][j]) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for (int i = 1; i < rows; i++) {
if (0 == matrix[i][0]) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = 0;
}
}
}
for (int i = 0; i < cols; i++) {
if (0 == matrix[0][i]) {
for (int j = 0; j < rows; j++) {
matrix[j][i] = 0;
}
}
}
if (0 == zeroH) {
for (int j = 0; j < cols; j++) {
matrix[0][j] = 0;
}
}
}
Jerky Lu wechat
欢迎加入微信公众号